package com.example.ayelet;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.ayelet.Imagelabels.ImageAndLabel;
import com.example.ayelet.Imagelabels.ImageAndLabels;

public class ChoosePhotosActivity extends Activity {

	private static final int RESULT_LOAD_IMAGE = 1;
	Uri currentImage = null;
	ImageView currentImageView;
	EditText labelEditText;
	ImageAndLabels.Builder imagelabelsBuilder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.choose_photos);
		imagelabelsBuilder = ImageAndLabels.newBuilder();
		currentImageView = (ImageView) findViewById(R.id.current_image);
		labelEditText = (EditText) findViewById(R.id.label);
		if (currentImage == null) {
			pickImage();
		}
	}

	protected void pickImage() {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

		startActivityForResult(i, RESULT_LOAD_IMAGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			currentImage = selectedImage;
			currentImageView.setImageURI(currentImage);

			// String picturePath contains the path of selected Image
		}
	}
	
	public void addCurrentImage() {
		String label = labelEditText.getText().toString();
		if (label.equals("")) {
			return;
		}
		ImageAndLabel imagelabel = ImageAndLabel.newBuilder().setLabel(label)
				.setUri(currentImage.toString()).build();
		imagelabelsBuilder.addImages(imagelabel);
		labelEditText.setText("");
	}

	public void nextClicked(View v) {
		addCurrentImage();
		pickImage();
	}

	public void doneClicked(View v) {
		addCurrentImage();
		Intent intent = new Intent();
		intent.putExtra("labels", imagelabelsBuilder.build().toByteArray());
		setResult(LearnEnglish.AMIR_ACTIVITY, intent);
		finish();
	}
}
